package com.nyist.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

	 public void sendMail(String mail,String url) {
	    	System.out.println(mail+"========="+url);
	    	
	    	//加载配置文件 ，其中有SMTP 服务器名 发信人的地址  和密码
	    	InputStream is = this.getClass().getResourceAsStream("/mailInfo.properties");
	    	
	    	Properties prop = new Properties();
	    	try {
				prop.load(is);//加载资源文件
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	    	
	        String msgText = "请点击下面的连接激活用户，如果不能点击请手动复制到地址栏中执行\n" + url;
	        String smtpHost = prop.get("smtpHost").toString();//SMTP服务器名
	        String from = prop.get("mailName").toString();//发信人地址
	        String pwd = prop.get("pwd").toString();//密码
	        String to = mail;//收信人地址
	        // 创建properties对象
	        Properties props = new Properties();
	        //创建邮件服务器
	        props.put("mail.smtp.host", smtpHost);
	        props.put("mail.smtp.auth", "true");

	        //取得默认的Session
	        Session session = Session.getDefaultInstance(props, null);

	        // 创建一条信息，并定义发信人地址和收信人地址
	        MimeMessage message = new MimeMessage(session);

	        try {
	            message.setFrom(new InternetAddress(from));

	            InternetAddress[] address = {new InternetAddress(to)};

	            message.setRecipients(Message.RecipientType.TO, address);

	            message.setSubject("激活注册用户");//设定主题

	            message.setSentDate(new Date());//设定发送时间

	            message.setText(msgText);//把前面定义的msgText中的文字设定为邮件正文的内容

	            message.saveChanges(); // implicit with send()
	            //设置协议
	            Transport transport = session.getTransport("smtp");
	            //发信人地址，用户名，密码
	            transport.connect(smtpHost, from, pwd);
	            System.out.println("地址"+smtpHost+"用户名"+from+"密码"+pwd);
	            transport.sendMessage(message, message.getAllRecipients());
	            transport.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
}
